/**    
 * 文件名：JsonUploadFileAction.java    
 *    
 * 版本信息：    
 * 日期：2014-6-6    
 * Copyright Corporation 2014     
 * 版权所有    
 *    
 */
package com.starbaba.core.web.struts2;

import java.util.Enumeration;
import java.util.List;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.system.attach.dao.UploadAttachStrategy;
import com.starbaba.system.attach.model.AttachVO;

/**
 * @Description:json上传通用类，目前只支持单文件上传（如果一个页面上有多个上传表单的话也可以支持
 * @author :royoan
 * @since :2014-6-6 上午10:27:08
 * @version :0.0.1
 */
@SuppressWarnings({"serial", "unchecked"})
public class JsonUploadFileAction extends BaseBatchAction {
	
	public static String MESSAGE_SUCCESS = "上传成功";
	
	private String servicecode;    //上传业务标识，必填
    
	
	public JsonUploadFileAction(){
	}
	
	/**
	 * 上传文件，只支持单个文件上传
	 * 
	 * @throws Exception
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-11-5 上午10:27:34
	 * @version V1.0
	 */
	public void upload() throws Exception {
		//获取页面上的参数
        MultiPartRequestWrapper request = (MultiPartRequestWrapper)Struts2Utils.getRequest();
        
        ExtJsonResult<AttachVO> result = new ExtJsonResult<AttachVO>();
        String errmsg = null;
        
        if(ServletFileUpload.isMultipartContent(request)) {
        	try {
//        		String servicecode = request.getParameter("servicecode");
            	Assert.hasText(servicecode, "参数servicecode不能为空");
            	
            	Enumeration<String> fileInputIds = request.getFileParameterNames();
    	        Assert.isTrue(fileInputIds.hasMoreElements(), "上传表单内容为空!");
    	        
    	        //获取了上传文件表单的id
    	        String fieldName = fileInputIds.nextElement();
    	        log.info("获取上传文件表单域的id： " + fieldName);
    	        
    	        List<AttachVO> rtnList = (List<AttachVO>) getService().doProcess(new UploadAttachStrategy(request, fieldName, servicecode, getUserVO()));
    	        if(!CollectionUtils.isEmpty(rtnList)) {
    	        	result.setData(rtnList.get(0));
    	        	rtnList.clear();
    	        }
    	        
			} catch (Exception e) {
				log.error(e, e);
				errmsg = "上传失败！失败原因：" + e.getMessage();
			}
	        
        } else {
        	errmsg = "表单mime类型不正确，请设置enctype=\"multipart/form-data\"";;
        }
        
        if(errmsg != null) {
        	result.setStatus(ERROR);
        	result.setMessage(errmsg);
        } else {
        	result.setStatus(SUCCESS);
        	result.setMessage(MESSAGE_SUCCESS);
        	
        }
    	sendJsonMessage(result);
    }


	public String getServicecode() {
		return servicecode;
	}

	public void setServicecode(String servicecode) {
		this.servicecode = servicecode;
	}
	
}
